package com.carlo.service.impl;

import java.util.List;

import microsoft.exchange.webservices.data.core.enumeration.property.BodyType;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.property.complex.EmailAddress;
import microsoft.exchange.webservices.data.property.complex.MessageBody;

import org.apache.commons.lang3.StringUtils;

import com.carlo.bean.MailCfg;
import com.carlo.service.AbstractMail;
import com.carlo.service.ISend;

/**
 * 
* @ClassName: ExchangeSendImpl 
* @Description: 使用Exchange协议发送邮件 
* @author carlo
* @date 2018年2月24日 下午5:45:46
 */
public class ExchangeSendImpl extends AbstractMail implements ISend {
	
	public void send(MailCfg mailCfg, String subject, String body,
			List<String> tos, List<String> ccs, List<String> attachments)
			throws Exception {
		this.initExchangeService(mailCfg.getAccount(), mailCfg.getPwd(),mailCfg.getServer_name());
		this.doSend(subject, body, mailCfg.getMail_addr(), tos, ccs, attachments);
	}
	
	/**
	 * 
	* @Title: doSend 
	* @Description: 使用exchange协议发送邮件 
	* @param @param subject		邮件标题
	* @param @param body		邮件正文内容
	* @param @param sender		发送方邮箱账号
	* @param @param tos			收件人
	* @param @param ccs			抄送给ccs
	* @param @param attachments	附件
	* @param @throws Exception    设定文件 
	* @return void    返回类型 
	* @author carlo
	* @throws
	 */
	public void doSend(String subject,String body,String sender, List<String> tos, List<String> ccs,
			 List<String> attachments) throws Exception {
		EmailMessage msg = new EmailMessage(this.service);
		if(StringUtils.isEmpty(sender)){
			throw new Exception("发送方邮箱账号为空");
		}
		if(null == tos || tos.isEmpty()){
			throw new Exception("收件人列表不能为空");
		}
		msg.setFrom(new EmailAddress(sender));
		
		msg.setSubject(subject);
		MessageBody messageBody = MessageBody.getMessageBodyFromText(body);
		messageBody.setBodyType(BodyType.HTML);
		msg.setBody(messageBody);
		//设置收件人
		for (String to : tos) {
			msg.getToRecipients().add(to);
		}
		//添加抄送人
		if(null != ccs && !ccs.isEmpty()){
			for (String cc : ccs) {
				 msg.getCcRecipients().add(cc);
				}
		}
		//添加附件
		if(null != attachments && !attachments.isEmpty()){
			for(String attachment:attachments){
				if (StringUtils.isNotEmpty(attachment)) {
					msg.getAttachments().addFileAttachment(attachment);
				}
			}
		}
		
		msg.send();
	}
	

}
